package com.hxzy.util;




import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;



import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;


public class DbHelper {




    public Connection getConnection()  {
        DataSource dateSource = DataSourceHelper.getDateSource();
        try {
            return dateSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //自定义链接方法
    public Connection get(){
        DataSource dateSource = DataSourceHelper.getDateSource();
        try {
            return dateSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //自定义DML操作
    public int   updateSql(String sql,Object...params){
        Connection connection=null;
        connection = this.get();
        QueryRunner queryRunner=new QueryRunner();
        try {
            return queryRunner.update(connection,sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }

    //执行DML操作的方法
    public  int  executeUpdate(String sql,Object...params){
        Connection connection=null;
        try {
            connection = this.getConnection();
            QueryRunner queryRunner=new QueryRunner();
            int update = queryRunner.update(connection, sql, params);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }



    //自定义通用查询方法，定义了如何从resultSet结果集中获取数据并转换成对应的 对象
    public <T> Optional<T> executeQuery(String sql, ResultSetHandler<T> handler, Object params ){
        Connection connection = null;
        try {
            connection = this.getConnection();
            QueryRunner queryRunner=new QueryRunner();
            T query = queryRunner.query(connection, sql, handler, params);
            return Optional.of(query);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                   e.printStackTrace();
                }
            }
        }
    }

}
